package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.DeptmentMultiListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DepartmentContent;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;

/**
 * 部门多选列表
 * 开发者: HuXiaoDan
 * 日期: 2017/1/6 17:11
 */
public class DeptmentMultiListFragment extends BaseListFragment {

  protected static final String EXTRA_CODE =
      "com.isunland.managesystem.ui.DeptmentMultiListFragment.EXTRA_CODE";

  private CurrentUser mUser;
  private DeptmentMultiListAdapter mAdapter;
  private DepartmentContent[] mcontents;
  private boolean isBat = false;//当前是否是全选，默认为false
  private Menu mMenu;//菜单
  private String mDeptCodes;//用来反选的code

  @Override public void onCreate(Bundle savedInstanceState) {
    mUser = CurrentUser.newInstance(getActivity());
    isBat = false;
    mDeptCodes = getArguments().getString(EXTRA_CODE);
    super.onCreate(savedInstanceState);
  }

  @Override public String getUrl() {
    return ApiConst.ULR_DEPT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mUser.getMemberCode());
    params.put("isPaging", "0");
    params.put("style", "tree");
    params.put("postKindCodes", "'positionType01'");
    params.put("orderField", "porg_code,order_no");
    params.put("orderSeq", "asc");
    params.put("staffCode", mUser.getJobNumber());
    params.put("type", "mobile");//处理考勤汇总韦加公司可以查询出两个子公司部门
    return params;
  }

  @Override public void resolveResponse(String json) {
    DepartmentContent[] contents = new Gson().fromJson(json, DepartmentContent[].class);
    if (mcontents == null) {
      mcontents = new DepartmentContent[contents.length];
    }
    mcontents = contents;
    setAdapter(contents);
  }

  public void setAdapter(DepartmentContent[] contents) {
    HashMap<String, Boolean> map = getDeptMap(mDeptCodes);
    if (mAdapter == null) {
      mAdapter = new DeptmentMultiListAdapter(getActivity(), contents, map);
    }
    setListAdapter(mAdapter);
    ((DeptmentMultiListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_multi_confirm, menu);
    mMenu = menu;
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        getActivity().finish();
        return true;

      case R.id.menu_item_confirm:
        if (mAdapter != null) {
          StringBuilder bufferDepCode = new StringBuilder();
          StringBuilder bufferDepName = new StringBuilder();
          for (int i = mAdapter.getCount() - 1; i >= 0; i--) {
            DepartmentContent contents = mAdapter.getItem(i);
            if (contents == null) continue;
            String name = contents.getOrgName();
            String code = contents.getOrgCode();
            if (mAdapter.isCheckedItem(code)) {
              if (bufferDepCode.length() > 0) {
                bufferDepCode.append(",").append("'" + code + "'");
              } else {
                bufferDepCode.append("'" + code + "'");
              }

              if (bufferDepName.length() > 0) {
                bufferDepName.append(",").append(name);
              } else {
                bufferDepName.append(name);
              }
            }
          }

          if (bufferDepName == null || bufferDepName.length() == 0) {
            ToastUtil.show("请选择部门");
            return false;
          }
          Intent i = new Intent();
          i.putExtra(SearchPersonMultipleFragment.EXTRA_JOB, bufferDepCode.toString());
          i.putExtra(SearchPersonMultipleFragment.EXTRA_NAME, bufferDepName.toString());
          LogUtil.i("name===" + bufferDepName.toString() + ",id==" + bufferDepCode.toString());
          getActivity().setResult(Activity.RESULT_OK, i);
          getActivity().finish();
        }
        break;
      //全选
      case R.id.menu_item_bat:
        HashMap<String, Boolean> map;
        if (isBat) {
          isBat = false;
          mMenu.getItem(0).setIcon(R.drawable.bat);
          map = new HashMap<>();
        } else {
          isBat = true;
          mMenu.getItem(0).setIcon(R.drawable.cancle);
          mMenu.getItem(0).setTitle("撤销");
          map = getDeptMap("");
        }
        mAdapter = new DeptmentMultiListAdapter(getActivity(), mcontents, map);
        setListAdapter(mAdapter);
        ((DeptmentMultiListAdapter) getListAdapter()).notifyDataSetChanged();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  public HashMap<String, Boolean> getDeptMap(String deptCodes) {
    HashMap<String, Boolean> map = new HashMap<>();

    if (!TextUtils.isEmpty(deptCodes)) {
      //反选，deptCodes不为空
      String[] array = deptCodes.split("'");
      if (array.length > 0) {
        for (String deptcod : array) {
          if (!",".equalsIgnoreCase(deptcod)) {
            map.put(deptcod, true);
          }
        }
      }
    } else {
      if (mAdapter != null) {
        for (int i = 0; i < mAdapter.getCount(); i++) {
          map.put(mAdapter.getItem(i).getOrgCode(), true);
        }
      }
    }

    return map;
  }

  public static DeptmentMultiListFragment newInstance(String deptCodes) {

    Bundle args = new Bundle();
    args.putString(EXTRA_CODE, deptCodes);
    DeptmentMultiListFragment fragment = new DeptmentMultiListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
